package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: Bbz
 * @verson: 1.0
 * @Date: 2023/7/10 11:39
 * 使用springCache的注解方式缓存数据
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 套餐信息查询分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page:{},pageSize:{},name:{}",page,pageSize,name);
        //构造分页构造器
        Page<Setmeal> setmealPage = new Page<>(page,pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>(page,pageSize);

        //构造条件过滤器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.eq(name!=null,Setmeal::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行查询
        setmealService.page(setmealPage,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");
        List<Setmeal> records = setmealPage.getRecords();

        List<SetmealDto> list=records.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }

    /**
     * 保存套餐信息
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",key = "#setmealDto.getCategoryId()+'_'+#setmealDto.getStatus()")
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        ////动态来构造一个key
        //String key="dish_"+setmealDto.getCategoryId()+"_"+setmealDto.getStatus();
        ////每次更新数据清除缓存
        //redisTemplate.delete(key);

        log.info("保存的信息：{}",setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("套餐添加成功");
    }


    /**
     * 根据id查询，  回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getByIdSetmealDto(@PathVariable Long id){
        log.info("查询的id:{}",id);
        SetmealDto setmealDto=setmealService.getByIdWithDishs(id);
         return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",key = "#setmealDto.getCategoryId()+'_'+#setmealDto.getStatus()")
    @PutMapping
    public R<String> updateSetmealWithDishs(@RequestBody SetmealDto setmealDto){
        ////动态来构造一个key
        //String key="dish_"+setmealDto.getCategoryId()+"_"+setmealDto.getStatus();
        ////每次更新数据清除缓存
        //redisTemplate.delete(key);

        log.info("修改的信息为：{}",setmealDto);
        setmealService.updateWithDishs(setmealDto);
        return R.success("修改套餐成功");
    }

    @PostMapping("/status/{status}")
    public R<String> enable(@PathVariable Integer status,Long[] ids){
        log.info("status:{},ids:{}",status,ids);
        for (Long id : ids) {
            setmealService.openOrClose(status,id);
        }
        return R.success("修改成功");
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//表示清理所有套餐数据
    public R<String> delete(Long[] ids){
        for (Long id : ids) {
            ////清除缓存 手动精确清理某一个套餐数据
            //Setmeal setmeal = setmealService.getById(id);
            ////动态来构造一个key
            //String key="setmealCache::"+setmeal.getCategoryId()+"_"+setmeal.getStatus();
            //System.out.println(key);
            //redisTemplate.delete(key);


            log.info("删除的id:{}",id);
            setmealService.deleteWithDishs(id);
        }
        return R.success("删除成功");
    }

    /**
     * 查询商务套餐列表  状态 0:停用 1:启用
     * @param categoryId
     * @param status
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Long categoryId,Integer status){
        List<Setmeal> list=null;

        ////动态来构造一个key
        //String key="dish_"+categoryId+"_"+status;
        //
        ////先从redis中获取缓存数据
        //list = (List<Setmeal>) redisTemplate.opsForValue().get(key);
        ////如果存在，直接返回,无需查询数据库
        //if(list!=null){
        //    return R.success(list);
        //}
        log.info("查询的套餐分类id是,{},status:{}",categoryId,status);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId,categoryId);
        queryWrapper.eq(Setmeal::getStatus,status);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        list = setmealService.list(queryWrapper);

        ////如果不存在需要查询数据库，将查询到的数据库缓存到Redis 缓存60分钟
        //redisTemplate.opsForValue().set(key,list,60, TimeUnit.MINUTES);

        return R.success(list);
    }


}
